"""
Test that when a projection from a volume is registered to the
volume that it converges to the right solution (best case registration scenario)

"""
import pythonRegistration as pr
from numpy import array, ones
import itk
import vtk
import ImageCompare

reload(pr)

reg=pr.registration()
reg.verbose = False

fixedFileName = 'C:/Lib/JointTrack/branches/bryan/Images/ushortim080-LAT.tif'
volFileName = 'C:/Lib/jointtrack/branches/TestData/vert1.vtk'
calFileName = 'C:/Lib/JointTrack/branches/bryan/Tests/good_cal.txt'
saveFileName = fixedFileName[:-4]+'_out.png'

reg.SetFixedImageFileName(fixedFileName)
reg.SetVolumeFileName(volFileName)

#reg.SetCalibration(calFileName)

#Set the moving image to be black on white to match the fixed image
reg.SetBlackOnWhiteMovingImage()

metric = itk.MeanSquaresImageToImageMetric.IF2IF2.New()
reg.SetImageMetric(metric)

reg.SetWindowNames()

reg.InitializeRegistration()
#reg.movingImageInteractor.Disable()

# This portion of the code clips the mace with the vtkPlanes implicit
# function.  The clipped region is colored green.
planes = vtk.vtkPlanes()
clipper = vtk.vtkClipVolume()
clipper.SetInput(0,reg.VolumeReader.GetOutput())
clipper.SetClipFunction(planes)
clipper.InsideOutOn()
selectMapper = vtk.vtkVolumeTextureMapper3D()
selectMapper.SetInputConnection(clipper.GetOutputPort())
selectActor = vtk.vtkVolume()
selectActor.SetMapper(selectMapper)
selectActor.GetProperty().SetColor(0, 1, 0)
selectActor.VisibilityOff()
selectActor.SetScale(1.01, 1.01, 1.01)

# The box widget observes the events invoked by the render window
# interactor.  These events come from user interaction in the render
# window.
boxWidget = vtk.vtkBoxWidget()
boxWidget.SetInteractor(reg.movingImageInteractor)
boxWidget.SetPlaceFactor(1.0)

# As the box widget is interacted with, it produces a transformation
# matrix that is set on the actor.
t = vtk.vtkTransform()
def TransformActor(obj, event):
    global t
    obj.GetTransform(t)
    reg.volume.SetUserTransform(t)

# Place the interactor initially. The actor is used to place and scale
# the interactor. An observer is added to the box widget to watch for
# interaction events. This event is captured and used to set the
# transformation matrix of the actor.
boxWidget.SetProp3D(reg.volume)
boxWidget.PlaceWidget()
boxWidget.AddObserver("InteractionEvent", TransformActor)

pose = array((0,0,0,0,-90,0))
reg.SetPose(pose)
reg.StartInteraction()

reg.SaveMovingImage(saveFileName)

#return 0 if they match, 1 otherwise.
comp = 0

#Test for positive match
assert comp==0

if comp == 0:
    print "Test Success!"
else:
    print "Test Failure!"

